﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;

namespace SharpSNS.Auth
{
    /// <summary>
    /// Encapsulates the OpenAuth API methods
    /// </summary>
    public class Auth
    {
        /// <summary>
        /// Executes the /clientLogin API method and returns the result
        /// </summary>
        /// <param name="devKey">Developer API key</param>
        /// <param name="loginId">Login Id</param>
        /// <param name="pwd">Password</param>
        /// <returns>Returns the response from the API server</returns>
        public static ClientLoginResponse ClientLogin(string devKey, string loginId, string pwd)
        {
            byte[] xmlBytes = Wrapper.clientLogin(devKey, loginId, pwd);
            using (MemoryStream ms = new MemoryStream(xmlBytes))
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(ms);
                XmlNode respNode = xmlDoc["response"];
                return new ClientLoginResponse(respNode, pwd);
            }
        }

        /// <summary>
        /// Calls the startOSCARSession API method based on the clientLogin response
        /// </summary>
        /// <param name="devKey">Developer key</param>
        /// <param name="clientLoginResponse">clientLogin response object</param>
        /// <returns>Returns a StartOscarSessionResponse containing the BOSS data</returns>
        public static StartOscarSessionResponse StartOscarSession(string devKey, ClientLoginResponse clientLoginResponse)
        {
            long ts = Epoch.GetDifference(DateTime.Now) + clientLoginResponse.TimeDifference;
            Console.WriteLine(ts.ToString());
            byte[] xmlBytes = Wrapper.startOSCARSession(clientLoginResponse.AuthToken, devKey, ts, clientLoginResponse.SessionKey);
            using (MemoryStream ms = new MemoryStream(xmlBytes))
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(ms);
                XmlNode respNode = xmlDoc["response"];
                return new StartOscarSessionResponse(respNode);
            }
        }
    }
}
